package catchData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

import util.DateGroup;

/**
 * @author suwy
 * @date 2013-11-27
 * @todo TODO
 */
public class CatchOa {

	private static Logger log = Logger.getLogger(CatchOa.class);
	private static HttpClient client;
	private static final String LOGIN_PAGE = "http://192.168.0.201/";
	private static final String HOST = "192.168.0.201";
	private static final int num = 1;//223;
	private static final String PATH = "F:\\download";

	private void initHttpClient() {
		if (client == null) {
			MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
			client = new HttpClient(connectionManager);
			// client.getHostConfiguration().setHost(HOST, PORT, "http"); //
			// 配置服务器参量
			client.getParams().setCookiePolicy(
					CookiePolicy.BROWSER_COMPATIBILITY); // 配置Cookie策略为浏览器默认策略
			client.getParams().setParameter(
					"http.protocol.single-cookie-header", true);
			client.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
			client.getHttpConnectionManager().getParams().setConnectionTimeout(
					300000);
			client.getHttpConnectionManager().getParams().setSoTimeout(300000);
		}
	}

	private void setHeaders(HttpMethod method) {
		method.getParams().setParameter("http.protocol.cookie-policy",
				CookiePolicy.BROWSER_COMPATIBILITY);
		method.setRequestHeader(
						"accept",
						"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		method.setRequestHeader("referer", LOGIN_PAGE);
		method.setRequestHeader("accept-encoding",
				"gzip,deflate,sdch");
		method.setRequestHeader("accept-language", "zh-CN,zh;q=0.8");
		method.setRequestHeader("content-type",
				"application/x-www-form-urlencoded");
		method.setRequestHeader(
						"user-agent",
						"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
		method.setRequestHeader("host", HOST);
		method.setRequestHeader("connection", "Keep-Alive");
		method.setRequestHeader("cache-control", "no-cache");
		log.info(getCookieString());
		method.setRequestHeader("Cookie", getCookieString());
	}

	private String getCookieString() {
		Cookie[] cookies = client.getState().getCookies();
		StringBuilder builder = new StringBuilder();
		for (Cookie cookie : cookies) {
			builder.append(cookie.getDomain()).append(":").append(
					cookie.getName()).append("=").append(cookie.getValue())
					.append(";").append(cookie.getPath()).append(";").append(
							cookie.getExpiryDate()).append(";").append(
							cookie.getSecure()).append(";/n");
		}
		return builder.toString();
	}
	
	private void saveDataFile(String sFolder, String data, long lid) {
		saveDataFile(sFolder, data, lid + "");
	}

	private void saveDataFile(String sFolder, String data, String sid) {
		File folder = new File(sFolder);
		if (!folder.exists()) folder.mkdirs();
		PrintWriter out = null;
		String saveFile = sFolder + "/" + sid + ".html";
		try {
			out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(
					saveFile), "gbk"));
			out.println(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			log.info("【" + DateGroup.getNow() + "】 保存文件成功！"
					+ saveFile.replaceAll("\\\\", "/"));
		}
	}


	public static void main(String[] args) {
		String loginURL = "http://192.168.0.201/csl/check?username=administrator&userpwd=147258";
		String str = "";
		GetMethod get = null;
		GetMethod get1 = null;
		try {
			CatchOa instance = new CatchOa();
			instance.initHttpClient();
			get = new GetMethod(loginURL);
			instance.setHeaders(get);
			client.executeMethod(get);
			str = get.getResponseBodyAsString();
			for(int i=1; i<= num; i++) {
				get1 = new GetMethod("http://192.168.0.201/csl/query?action=run&uid=" + i
						+ "&sdate=2013-11-01&edate=2013-11-27");
				instance.setHeaders(get1);
				client.executeMethod(get1);
				str = get1.getResponseBodyAsString();
//				instance.saveDataFile(PATH, str, i);
				log.info(str);
				get1.releaseConnection();
			}
			get.releaseConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
